package io.bdmc.modules.api.controller;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.apache.shiro.crypto.hash.Sha256Hash;
import io.bdmc.common.utils.DateUtils;
import io.bdmc.common.utils.ImageUtil;
import io.bdmc.common.utils.MyMap;
import io.bdmc.common.utils.MyPage;
import io.bdmc.common.utils.R;
import io.bdmc.common.utils.WebTokenUtil;
import io.bdmc.common.wechatsdk.WeChatUtil;
import io.bdmc.modules.api.annotation.AuthIgnore;
import io.bdmc.modules.bss.entity.SmkAlarm;
import io.bdmc.modules.bss.entity.SmkDevice;
import io.bdmc.modules.bss.entity.SmkMaint;
import io.bdmc.modules.bss.entity.SmkMuser;
import io.bdmc.modules.bss.entity.SmkShop;
import io.bdmc.modules.bss.model.AlarmParam;
import io.bdmc.modules.bss.model.ShopLocation;
import io.bdmc.modules.bss.model.ShopParam;
import io.bdmc.modules.bss.service.ISmkAlarmService;
import io.bdmc.modules.bss.service.ISmkDeviceService;
import io.bdmc.modules.bss.service.ISmkMaintService;
import io.bdmc.modules.bss.service.ISmkMuserService;
import io.bdmc.modules.bss.service.ISmkShopService;
import io.bdmc.modules.sys.entity.SysLog;
import io.bdmc.modules.sys.service.SysLogService;

@RestController
@RequestMapping(value = "/api/maint")
public class MaintenController extends BaseApiController {

    @Autowired
    private ISmkMuserService _muserSvs;
    @Autowired
    private ISmkMaintService _maintSvs;
    @Autowired
    private ISmkShopService _shopSvs;
    @Autowired
    private ISmkDeviceService _devSvs;
    @Autowired
    private ISmkAlarmService _alarmSvs;
    @Autowired
    private SysLogService _logSvs;

    @AuthIgnore
    @PostMapping(value = "/bind")
    public R bind(@RequestBody Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("mobile")) || StringUtils.isEmpty(map.get("password"))
                || StringUtils.isEmpty(map.get("openid"))) {
            return R.error(-1, "参数错误");
        }
        String openid = String.valueOf(map.get("openid"));
        String wxImage = String.valueOf(map.get("wxImage"));
        //String wxName = String.valueOf(map.get("wxName"));
        String mobile = String.valueOf(map.get("mobile"));
        String password = String.valueOf(map.get("password"));
        QueryWrapper<SmkMuser> w1 = new QueryWrapper<SmkMuser>();
        w1.eq("mobile", mobile);
        SmkMuser muser = _muserSvs.getOne(w1);
        // 账号不存在、密码错误
        if (muser == null || !muser.getPassword().equals(new Sha256Hash(password, mobile).toHex())) {
            return R.error(-1, "账号或密码不正确");
        }

        muser.setWxImage(wxImage);
        muser.setWxName(muser.getUsername());
        muser.setOpenid(openid);
        muser.setCreateTime(LocalDateTime.now());
        _muserSvs.updateById(muser);
        SmkMaint sm = _maintSvs.getById(muser.getMaintId());
        String token = WebTokenUtil.createJWT(muser.getUserId(), muser.getOpenid(), sm.getDeptId(), muser.getWxName(),
                36000000);
        Map<String, Object> respMap = new HashMap<>();
        respMap.put("wxName", muser.getUsername());
        respMap.put("wxImage", wxImage);
        respMap.put("openid", openid);
        respMap.put("dep_id", sm.getDeptId());
        respMap.put("mobile", muser.getMobile());
        respMap.put("username", muser.getUsername());
        respMap.put("maintName", sm.getMaintName());
        respMap.put("token", token);
        return R.ok().putData(respMap);
    }

    @PostMapping(value = "/unbind")
    public R unbind(@RequestBody Map<String, Object> map) {
        int id = Integer.valueOf(request.getAttribute("user_id").toString());
        SmkMuser u = _muserSvs.getById(id);
        if (u != null) {
            u.setWxImage("");
            u.setWxName("");
            u.setOpenid("");
            boolean b = _muserSvs.updateById(u);
            return R.trueOfFalse(b);
        }
        return R.error(-1, "参数错误");
    }

    // 获取商户信息
    @PostMapping(value = "/shops")
    public R getShops(@RequestBody ShopParam param) {
        Long dep_id = Long.valueOf(request.getAttribute("dep_id").toString());
        param.setDeptId(dep_id);
        MyPage<SmkShop> myPage = new MyPage<SmkShop>(param.getCurrent(), param.getSize());
        MyPage<ShopLocation> pageData = _shopSvs.getByDepId(myPage, param);
        return R.ok().putData(MyMap.ok(pageData.getRecords(), pageData.getTotal()));
    }

    // 根据商户id获取设备信息
    @PostMapping(value = "/devices")
    public R getDevices(@RequestBody Map<String, Object> map) {
        int id = Integer.valueOf(String.valueOf(map.get("id")));
        QueryWrapper<SmkDevice> w1 = new QueryWrapper<SmkDevice>();
        w1.eq("shop_id", id);
        List<SmkDevice> devs = _devSvs.list(w1);
        List<Map<Object, Object>> list = new LinkedList<>();
        for (SmkDevice dev : devs) {
            Map<Object, Object> tempmap = new HashMap<>();
            tempmap.put("imei", dev.getImei());
            tempmap.put("devName", dev.getDevName());
            tempmap.put("devModel", dev.getDevModel());
            tempmap.put("devStatus", dev.getDevStatus());
            tempmap.put("installPic", dev.getInstallPic());
            tempmap.put("installDate", dev.getInstallDate());
            tempmap.put("installAddr", dev.getInstallAddr());
            list.add(tempmap);
        }
        return R.ok().putData(MyMap.ok(list, list.size()));
    }

    // 根据商户id获取设备报警信息
    @PostMapping(value = "/alarm")
    public R getDevicesAlarm(@RequestBody Map<String, String> map) {
        int id = Integer.valueOf(String.valueOf(map.get("id")));
        List<SmkAlarm> alarms = _alarmSvs.wxSelectAlarmByShopId(id);
        return R.ok().putData(alarms);
    }

        // 获取报警信息
        @RequestMapping(value = "/alarmlist")
        public R alarmList(@RequestBody AlarmParam params) {
            Long dep_id = Long.valueOf(request.getAttribute("dep_id").toString());
            params.setDeptId(dep_id);
            MyPage<SmkAlarm> myPage = new MyPage<>(params.getCurrent(), params.getSize());
            MyPage<SmkAlarm> map = _alarmSvs.wxSelectAlarm(myPage, params);
            return R.ok().putData(MyMap.ok(map.getRecords(), map.getTotal()));
        }

    // 子单位信息
    @PostMapping(value = "/single_shop")
    public R getShopInfo(@RequestBody Map<String, String> map) {
        int id = Integer.valueOf(String.valueOf(map.get("id")));
        SmkShop shop = _shopSvs.getById(id);
        return R.ok().putData(shop);
    }

    @PostMapping(value = "/save_shop")
    public R saveShop(@RequestBody SmkShop bd) {
        boolean b = _shopSvs.saveOrUpdate(bd);
        if(b){
            SysLog log = new SysLog();
            log.setUsername(getLoginName());
            log.setIp(getLocalIp());
            log.setCreateDate(new Date());
            log.setOperation("更新店铺信息"+bd.getShopName());
            log.setParams(bd.toString());
            log.setTime(0L);
            log.setMethod("saveShop");
            _logSvs.save(log);
        }
        return R.trueOfFalse(b);
    }

    @PostMapping(value = "/bind_dev")
    public R bindDevice(@RequestBody Map<String, String> map) {
        String dev_imei = String.valueOf(map.get("imei"));
        String iccid = map.get("iccid");
        String installAddr = String.valueOf(map.get("installAddr"));
        Long shop_id = Long.valueOf(map.get("shopId").toString());
        SmkShop shop = _shopSvs.getById(shop_id);
        QueryWrapper<SmkDevice> w1 = new QueryWrapper<SmkDevice>();
        w1.eq("imei", dev_imei);
        SmkDevice dev = _devSvs.getOne(w1);
        if(dev==null){
            return R.error(-1, "设备不存在。");
        }
        if(dev.getShopId()!=null&&dev.getShopId()>0){
            return R.error(-1, "该设备已被绑定，请勿重复绑定。");
        }
        dev.setShopId(shop_id);
        dev.setInstallAddr(installAddr);
        dev.setDeptId(shop.getDeptId());
        dev.setInstallDate(LocalDateTime.now());
        dev.setIccid(iccid);
        boolean b = _devSvs.updateById(dev);
        if(b){
            SysLog log = new SysLog();
            log.setUsername(getLoginName());
            log.setIp(getLocalIp());
            log.setCreateDate(new Date());
            log.setOperation("绑定设备"+dev_imei+"到店铺"+shop.getShopName());
            log.setParams(dev_imei+","+iccid+","+installAddr+","+shop_id);
            log.setMethod("bindDevice");
            log.setTime(0L);
            _logSvs.save(log);
        }
        return R.trueOfFalse(b);
    }

    @PostMapping(value = "/unbind_dev")
    public R unbindDev(@RequestBody Map<String, String> map) {
        String dev_imei = map.get("imei");
        QueryWrapper<SmkDevice> w1 = new QueryWrapper<SmkDevice>();
        w1.eq("imei", dev_imei);
        SmkDevice dev = _devSvs.getOne(w1);
        dev.setShopId(0L);
        dev.setDeptId(1L);
        dev.setInstallAddr("");
        dev.setInstallDate(null);
        boolean b = _devSvs.updateById(dev);
        if(b){
            SysLog log = new SysLog();
            log.setUsername(getLoginName());
            log.setIp(getLocalIp());
            log.setCreateDate(new Date());
            log.setOperation("解除绑定设备"+dev_imei);
            log.setParams(dev_imei);
            log.setMethod("unbindDev");
            log.setTime(0L);
            _logSvs.save(log);
        }
        return R.trueOfFalse(b);
    }

    @PostMapping(value = "/getsign")
    public R getSign(@RequestBody Map<String, Object> map) {
        String url = String.valueOf(map.get("url"));
        if(url!=null&&url.length()>0){
            JSONObject sign = WeChatUtil.getSign(url);
            return R.ok().putData(sign);
        }
        return R.error(-1,"参数错误！");
    }

    @PostMapping("/picture")//设备安装照片
    public R installPicture(@RequestBody Map<String, String> map) {
        if(map.get("imei")==null||map.get("media_id")==null||map.get("lat")==null||map.get("lng")==null){
            return R.error(-1,"参数错误。");
        }
        String imei = map.get("imei");
        QueryWrapper<SmkDevice> w1 = new QueryWrapper<SmkDevice>();
        w1.eq("imei", imei);
        SmkDevice dev = _devSvs.getOne(w1);
        String media_id = map.get("media_id");

        String lat = map.get("lat");
        if(lat.length()>9){
            lat = lat.substring(0,9);
        }
        String lng = map.get("lng");
        if(lng.length()>10){
            lng = lng.substring(0,10);
        }
        
        String latLng = "北纬:"+lat+"°  东经:"+lng+"°";

        String path = WeChatUtil.downloadImage(media_id);
        if (!StringUtils.isEmpty(path)) {

            SmkShop s = _shopSvs.getById(dev.getShopId());
            Map<String, String> logoMap = new HashMap<String,String>();
            logoMap.put("time",  DateUtils.getNowLocalDateTime());
            logoMap.put("shopAddr",  s.getAddr());
            logoMap.put("shopName",  s.getShopName());
            logoMap.put("latLng",  latLng);
            String newImagePath = path.replace(media_id, media_id+"install");
            //打水印
            ImageUtil.markImageByText(logoMap,path,newImagePath,"JPG");
            dev.setInstallPic(newImagePath);
            boolean b = dev.updateById();
            if(b){
                SysLog log = new SysLog();
                log.setUsername(getLoginName());
                log.setIp(getLocalIp());
                log.setCreateDate(new Date());
                log.setOperation("上传设备安装图片");
                log.setParams("imei:"+imei+",path:"+path);
                log.setTime(0L);
                log.setMethod("installpicture");
                _logSvs.save(log);
            }
            return R.trueOfFalse(b);          
        }
        return R.error(-1, "设备安装图片上传失败。");
    }



    @PostMapping("/duty")
    public R dutyletter(@RequestBody Map<String, Object> map) {
        if(map.get("id")==null||map.get("media_id")==null||map.get("lat")==null||map.get("lng")==null){
            return R.error(-1,"参数错误。");
        }
        int id = Integer.valueOf(map.get("id").toString());
        String media_id = String.valueOf(map.get("media_id"));
        String lat = map.get("lat").toString();
        if(lat.length()>9){
            lat = lat.substring(0,9);
        }
        String lng = map.get("lng").toString();
        if(lng.length()>10){
            lng = lng.substring(0,10);
        }
        
        String latLng = "北纬:"+lat+"°  东经:"+lng+"°";
        String path = WeChatUtil.downloadImage(media_id);

        if (!StringUtils.isEmpty(path)) {
            SmkShop s = _shopSvs.getById(id);
            if (s == null) {
                return R.error(-1, "店铺不存在！");
            }
            Map<String, String> logoMap = new HashMap<String,String>();
            logoMap.put("time",  DateUtils.getNowLocalDateTime());
            logoMap.put("shopAddr",  s.getAddr());
            logoMap.put("shopName",  s.getShopName());
            logoMap.put("latLng",  latLng);
            String newImagePath = path.replace(media_id, media_id+"marks");
            //打水印
            ImageUtil.markImageByText(logoMap,path,newImagePath,"JPG");
            s.setDutyLetter(newImagePath);
            boolean b = _shopSvs.updateById(s);
            if(b){
                SysLog log = new SysLog();
                log.setUsername(getLoginName());
                log.setIp(getLocalIp());
                log.setCreateDate(new Date());
                log.setOperation("上传责任书");
                log.setParams("店铺:"+s.getShopName()+",path:"+newImagePath);
                log.setMethod("dutyletter");
                log.setTime(0L);
                _logSvs.save(log);
                return R.ok().putData(newImagePath);
            }
            return R.trueOfFalse(b);          
        }
        return R.error(-1, "店铺责任书上传失败。");
    }

    @PostMapping("/shop_pic")//上传店铺照片
    public R shopPicture(@RequestBody Map<String, Object> map) {
        if(map.get("id")==null||map.get("media_id")==null||map.get("lat")==null||map.get("lng")==null){
            return R.error(-1,"参数错误。");
        }
        int id = Integer.valueOf(map.get("id").toString());
        String media_id = String.valueOf(map.get("media_id"));
        String lat = map.get("lat").toString();
        if(lat.length()>9){
            lat = lat.substring(0,9);
        }
        String lng = map.get("lng").toString();
        if(lng.length()>10){
            lng = lng.substring(0,10);
        }
        
        String latLng = "北纬:"+lat+"°  东经:"+lng+"°";
        String path = WeChatUtil.downloadImage(media_id);

        if (!StringUtils.isEmpty(path)) {
            SmkShop s = _shopSvs.getById(id);
            if (s == null) {
                return R.error(-1, "店铺不存在！");
            }
            Map<String, String> logoMap = new HashMap<String,String>();
            logoMap.put("time",  DateUtils.getNowLocalDateTime());
            logoMap.put("shopAddr",  s.getAddr());
            logoMap.put("shopName",  s.getShopName());
            logoMap.put("latLng",  latLng);
            String newImagePath = path.replace(media_id, media_id+"marks");
            //打水印
            ImageUtil.markImageByText(logoMap,path,newImagePath,"JPG");
            s.setPicture(newImagePath);
            boolean b = _shopSvs.updateById(s);
            if(b){
                SysLog log = new SysLog();
                log.setUsername(getLoginName());
                log.setIp(getLocalIp());
                log.setCreateDate(new Date());
                log.setOperation("上传店铺照片");
                log.setParams("店铺:"+s.getShopName()+",path:"+newImagePath);
                log.setMethod("shopPicture");
                log.setTime(0L);
                _logSvs.save(log);
                return R.ok().putData(newImagePath);
            }
            return R.trueOfFalse(b);          
        }
        return R.error(-1, "店铺照片上传失败。");
    }

    @PostMapping("/shop_map")//上传店铺照片
    public R shopMap(@RequestBody Map<String, Object> map) {
        if(map.get("id")==null||map.get("media_id")==null){
            return R.error(-1,"参数错误。");
        }
        int id = Integer.valueOf(map.get("id").toString());
        String media_id = String.valueOf(map.get("media_id"));
        String path = WeChatUtil.downloadImage(media_id);

        if (!StringUtils.isEmpty(path)) {
            SmkShop s = _shopSvs.getById(id);
            if (s == null) {
                return R.error(-1, "店铺不存在！");
            }

            String newImagePath = path.replace(media_id, media_id+"map");
            s.setShopMap(newImagePath);
            boolean b = _shopSvs.updateById(s);
            if(b){
                SysLog log = new SysLog();
                log.setUsername(getLoginName());
                log.setIp(getLocalIp());
                log.setCreateDate(new Date());
                log.setOperation("上传店铺平面图");
                log.setParams("店铺:"+s.getShopName()+",path:"+newImagePath);
                log.setMethod("shopMap");
                log.setTime(0L);
                _logSvs.save(log);
                return R.ok().putData(newImagePath);
            }
            return R.trueOfFalse(b);          
        }
        return R.error(-1, "店铺照片上传失败。");
    }
}